module.exports = (app) => {
  const User = require("../models/User")
  const Video = require("../models/Video")
  const Danmu = require("../models/Danmu")
  const Comment = require("../models/Comment")
  const Message = require("../models/Message")

  const router = require("express").Router({
    // 合并父子路由路径参数
    mergeParams: true,
  })
  //资源路径
  app.use(
    "/admin/api/video",
    async (req, res, next) => {
      next()
    },
    router
  )
  //点赞相关
  router.post("/zan", async (req, res) => {
    let { _id, author } = req.body
    let video = await Video.findById(_id)
    let index = video.zanList.indexOf(author)
    if (index === -1) {
      video.zanList.push(author)
      res.send(video.zanList)
    } else {
      video.zanList.splice(index, 1)
      res.send(video.zanList)
    }
    await video.save()
  })
  //收藏
  router.post("/collect", async (req, res) => {
    let { _id, author } = req.body
    let video = await Video.findById(_id)
    let user = await User.findById(author)
    let index = video.collectList.indexOf(author)
    let userIndex = user.collectList.indexOf(_id)
    if (index === -1) {
      video.collectList.push(author)
      user.collectList.push(_id)
      res.send(video.collectList)
    } else {
      video.collectList.splice(index, 1)
      user.collectList.splice(userIndex, 1)
      res.send(video.collectList)
    }
    await video.save()
    await user.save()
  })

  //视频搜索
  router.get("/search", async (req, res) => {
    let { keyWord, page, sortBy } = req.query
    let reg = new RegExp(keyWord)
    let videos
    if (sortBy) {
      videos = await Video.find({ title: reg })
        .sort("-" + sortBy)
        .limit(8)
        .skip((page - 1) * 8)
        .populate("author", "nick")
    } else {
      videos = await Video.find({ title: reg })
        .limit(8)
        .skip((page - 1) * 8)
        .populate("author", "nick")
    }
    res.send(videos)
  })
  //排行榜
  router.get("/top", async (req, res) => {
    const data = await Video.find()
      .sort("-playCount")
      .limit(20)
      .populate("author", ["nick", "headUrl", "sign"])
    res.send(data)
  })
  //视频详情页
  router.get("/:_id", async (req, res) => {
    let _id = req.params._id
    let result = await Danmu.findOne({ player: _id })
    let danmuCount = result ? result.danmuList.length : 0
    let count = await Video.estimatedDocumentCount()
    let video = await Video.findById(_id).populate(["author", "type"])
    video.playCount += 1
    await Video.findByIdAndUpdate(_id, video)
    let skip = parseInt(Math.random() * (count - 3) + "")
    let otherVideos = await Video.find()
      .populate("author", "nick")
      .limit(4)
      .skip(skip)
    res.send({ video, otherVideos, danmuCount })
  })
}
